package com.ushio.capsuleservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushio.capsuleservice.mapper.ContainerMapper;
import com.ushio.capsuleservice.mapper.PlanMapper;
import com.ushio.capsuleservice.model.entity.Container;
import com.ushio.capsuleservice.model.entity.Plan;
import com.ushio.capsuleservice.service.PlanService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 计划服务实现类
 */
@Slf4j
@Service
public class PlanServiceImpl extends ServiceImpl<PlanMapper, Plan>  implements PlanService {
    
    @Autowired
    private PlanMapper planMapper;
    
    @Autowired
    private ContainerMapper containerMapper;
    
    @Override
    @Transactional
    public Plan createPlan(Plan plan) {
        try {
            plan.setCreatedTime(LocalDateTime.now());
            plan.setUpdatedTime(LocalDateTime.now());
            
            // 设置默认值
            if (plan.getStatus() == null) {
                plan.setStatus("pending");
            }
            if (plan.getColor() == null) {
                plan.setColor("#409EFF");
            }
            
            int result = planMapper.insert(plan);
            if (result > 0) {
                log.info("创建计划成功，ID: {}", plan.getId());
                return plan;
            } else {
                throw new RuntimeException("创建计划失败");
            }
        } catch (Exception e) {
            log.error("创建计划失败", e);
            throw new RuntimeException("创建计划失败：" + e.getMessage());
        }
    }
    
    @Override
    public List<Plan> getPlansByUserId(Long userId) {
        try {
            List<Plan> plans = planMapper.selectPlansByUserId(userId);
            
            // 为每个计划填充关联的容器ID列表
            for (Plan plan : plans) {
                QueryWrapper<Container> containerQuery = new QueryWrapper<>();
                containerQuery.eq("plan_id", plan.getId())
                            .ne("status", 0); // 排除已删除的容器
                List<Container> containers = containerMapper.selectList(containerQuery);
                
                List<Long> containerIds = containers.stream()
                    .map(Container::getId)
                    .collect(java.util.stream.Collectors.toList());
                plan.setContainerIds(containerIds);
            }
            
            return plans;
        } catch (Exception e) {
            log.error("获取计划列表失败", e);
            throw new RuntimeException("获取计划列表失败：" + e.getMessage());
        }
    }
    
    @Override
    public Plan getPlanById(Long planId) {
        try {
            Plan plan = planMapper.selectById(planId);
            if (plan != null) {
                // 填充关联的容器ID列表
                QueryWrapper<Container> containerQuery = new QueryWrapper<>();
                containerQuery.eq("plan_id", planId);
//                            .ne("status", 0); // todo -暂不考虑，排除已删除的容器
                List<Container> containers = containerMapper.selectList(containerQuery);
                
                List<Long> containerIds = containers.stream()
                    .map(Container::getId)
                    .collect(java.util.stream.Collectors.toList());
                plan.setContainerIds(containerIds);
            }
            return plan;
        } catch (Exception e) {
            log.error("获取计划详情失败", e);
            throw new RuntimeException("获取计划详情失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public Plan updatePlan(Long planId, Plan plan) {
        try {
            Plan existingPlan = planMapper.selectById(planId);
            if (existingPlan == null) {
                throw new RuntimeException("计划不存在");
            }
            
            // 更新字段
            if (plan.getTitle() != null) {
                existingPlan.setTitle(plan.getTitle());
            }
            if (plan.getDescription() != null) {
                existingPlan.setDescription(plan.getDescription());
            }
            if (plan.getCategory() != null) {
                existingPlan.setCategory(plan.getCategory());
            }
            if (plan.getDate() != null) {
                existingPlan.setDate(plan.getDate());
            }
            if (plan.getStartTime() != null) {
                existingPlan.setStartTime(plan.getStartTime());
            }
            if (plan.getEndTime() != null) {
                existingPlan.setEndTime(plan.getEndTime());
            }
            if (plan.getPriority() != null) {
                existingPlan.setPriority(plan.getPriority());
            }
            if (plan.getStatus() != null) {
                existingPlan.setStatus(plan.getStatus());
            }
            if (plan.getColor() != null) {
                existingPlan.setColor(plan.getColor());
            }
            
            existingPlan.setUpdatedTime(LocalDateTime.now());
            
            int result = planMapper.updateById(existingPlan);
            if (result > 0) {
                log.info("更新计划成功，ID: {}", planId);
                return existingPlan;
            } else {
                throw new RuntimeException("更新计划失败");
            }
        } catch (Exception e) {
            log.error("更新计划失败", e);
            throw new RuntimeException("更新计划失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public boolean deletePlan(Long planId) {
        try {
            Plan existingPlan = planMapper.selectById(planId);
            if (existingPlan == null) {
                throw new RuntimeException("计划不存在");
            }
            
            // 删除计划时，需要解绑所有关联的容器
            QueryWrapper<Container> containerQuery = new QueryWrapper<>();
            containerQuery.eq("plan_id", planId);
            List<Container> containers = containerMapper.selectList(containerQuery);
            
            for (Container container : containers) {
                container.setPlanId(null);
                container.setUpdatedTime(LocalDateTime.now());
                containerMapper.updateById(container);
            }
            
            int result = planMapper.deleteById(planId);
            if (result > 0) {
                log.info("删除计划成功，ID: {}", planId);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error("删除计划失败", e);
            throw new RuntimeException("删除计划失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public boolean batchUpdatePlans(List<Plan> plans) {
        try {
            for (Plan plan : plans) {
                plan.setUpdatedTime(LocalDateTime.now());
            }
            
            int result = planMapper.updateBatch(plans);
            log.info("批量更新计划成功，影响行数: {}", result);
            return result > 0;
        } catch (Exception e) {
            log.error("批量更新计划失败", e);
            throw new RuntimeException("批量更新计划失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public boolean bindContainer(Long planId, Long containerId) {
        try {
            // 检查计划是否存在
            Plan plan = planMapper.selectById(planId);
            if (plan == null) {
                throw new RuntimeException("计划不存在");
            }
            
            // 检查容器是否存在
            Container container = containerMapper.selectById(containerId);
            if (container == null) {
                throw new RuntimeException("容器不存在");
            }
            
            // 绑定容器到计划
            container.setPlanId(planId);
            container.setUpdatedTime(LocalDateTime.now());
            
            int result = containerMapper.updateById(container);
            if (result > 0) {
                log.info("容器绑定到计划成功，计划ID: {}, 容器ID: {}", planId, containerId);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error("绑定容器失败", e);
            throw new RuntimeException("绑定容器失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public boolean unbindContainer(Long planId, Long containerId) {
        try {
            // 检查容器是否存在且绑定到该计划
            Container container = containerMapper.selectById(containerId);
            if (container == null) {
                throw new RuntimeException("容器不存在");
            }
            
            if (!planId.equals(container.getPlanId())) {
                throw new RuntimeException("绑定关系不存在");
            }
            
            // 解绑容器
            container.setPlanId(null);
            container.setUpdatedTime(LocalDateTime.now());
            
            int result = containerMapper.updateById(container);
            if (result > 0) {
                log.info("容器解绑成功，计划ID: {}, 容器ID: {}", planId, containerId);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            log.error("解绑容器失败", e);
            throw new RuntimeException("解绑容器失败：" + e.getMessage());
        }
    }
}